package com.ganzi.ganziserver.rabbit.recevie;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ganzi.ganziserver.dao.FanCollectDao;
import com.ganzi.ganziserver.dao.FanStateDao;
import com.ganzi.ganziserver.dao.SchoolInformationDao;
import com.ganzi.ganziserver.service.QueryThreadService;
import com.ganzi.ganziserver.utils.GetTime;
import com.ganzi.ganziserver.utils.Topic;
import com.rabbitmq.client.Channel;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
public class RecevieState {

    private static Logger log = LoggerFactory.getLogger(RecevieState.class);

    @Autowired
    SchoolInformationDao schoolDao;
    @Autowired
    FanCollectDao collectDao;
    @Autowired
    FanStateDao fanStateDao;
    @Autowired
    QueryThreadService queryThreadService;

    @RabbitListener(queues = Topic.RECEVIE_STATE)
    public void process(Message message, Channel channel)throws IOException {
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        try {
            log.info("收到 在线-->：" + new String(message.getBody()));
            if (message.getBody().length <= 0) return;
            JSONObject info = (JSONObject) JSON.parse(message.getBody());
            String channelName = info.getString("channelName");
            if (StringUtils.isBlank(channelName)) return;
            Long id = schoolDao.findSchoolIdByQueue(channelName);
            if (id == null) {
                log.info("系统中没有对应通道的学校：" + channelName);
                return;
            }
            int state = info.getInteger("state");
            int schoolState = info.getInteger("schoolState");
            schoolDao.updateSchoolForOnline(channelName, schoolState);
            //处理单个ip上下线
            if (info.containsKey("ip")){
                String ip = info.getString("ip");
                if (StringUtils.isNotBlank(ip)) {
                    Long collectId = collectDao.findFanCollectIdByschoolIdAndIp(id, ip);
                    if (collectId != null) {
                        collectDao.updateFanCollectForOnline(collectId, state, GetTime.getNowTime());
                        setOnLineAndQueryThread(state,channelName,collectId,id);
                    } else {
                        log.info("找不到对应的采集器信息 ip:" + ip + "schoolId:" + id);
                    }
                }
            }
            //处理批量ip上下线(查询采集器在线的命令)
            if(info.containsKey("ipList")){
                JSONArray iplist = info.getJSONArray("ipList");
                if(iplist == null)return;
                for (int i = 0; i < iplist.size(); i++) {
                    String tempip = (String)iplist.get(i);
                    Long collectId = collectDao.findFanCollectIdByschoolIdAndIp(id,tempip);
                    if (collectId != null) {
                        collectDao.updateFanCollectForOnline(collectId, state, GetTime.getNowTime());
                        setOnLineAndQueryThread(state,channelName,collectId,id);
                    } else {
                        log.info("找不到对应的采集器信息 ip:" +tempip + "schoolId:" + id);
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            log.info("在线状态接收异常："+e.getMessage());
        }
    }

    public void setOnLineAndQueryThread(int state,String channelName,long collectId,long schoolId){
        try{
            if(state == 1){
                //采集器上下 创建线程发送查询命令发送查询命令 2019.4.11领导把采购的工作分配给我了 我TM准备离职
                Long schoolid = schoolDao.findSchoolIdByQueue(channelName);
                if(schoolid != null){
                    queryThreadService.sendQueryOrder(channelName,collectId,schoolId);
                }
            }else{
                //采集器离线 把所有盘管搞离线  停止查询线程
                queryThreadService.stopsendQueryOrder(channelName,collectId);
                fanStateDao.updateOnLine(collectId,2);
            }
        }catch (Exception e){
            e.printStackTrace();
            log.info("处理盘管在线状态和查询线程异常："+e.getMessage());
        }
    }
}
